package com.cbw.controller;

import com.cbw.bean.Message;
import com.cbw.mvc.ResponseBody;
import com.cbw.service.AdminService;
import com.cbw.util.JSONUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class AdminController {
    @ResponseBody("/admin/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){
        //1.接收参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2.调用Service传参数，并获取结果
        boolean result = AdminService.login(username, password);
        System.out.println("登录结果:"+result);
        //3.根据结果，准备不同的返回数据
        Message msg=null;
        if (result){
            //登录成功
            msg=new Message(0,"登录成功");//ajax收到的json{status:0,result:"登录成功"}
            //登录时间和登录ip的更新
            Date date = new Date();
            String ip = request.getRemoteAddr();//获取用户的远程地址(本机访问，ip不是ipv4格式的ip)
            AdminService.updateLoginTimeAndIp(username,date,ip);
            //登录用户存入session中,
            request.getSession().setAttribute("adminUsername",username);
        }else {
            msg=new Message(-1,"登录失败");//ajax收到的json//{status:0,result:"登录失败"}
        }
        String json = JSONUtil.toJSON(msg);//4.将数据(消息对象)转成json字符串
        return json;//5.将JSON回写给ajax
    }
}
